#include "SequencePlaybar.h"

#include <QTime>
#include <QMessageBox>

#include "ui_SequencePlaybar.h"
#include "ApplicationIcon.h"
#include "ActionListController.h"
#include "sequencerunner.h"
#include "ITimerService.h"

#define  TIME_REFRESH_MS   100  /**< update time for count-down display */

SequencePlaybar::SequencePlaybar( ActionListController &actionController, SequenceRunner &runner,
                                  ITimerService *timer, QWidget *parent) :
   QWidget(parent),
   ui(new Ui::SequencePlaybar),
   m_timer(timer),
   m_countDownMs(-1)
{
   ui->setupUi(this);
   ui->editButton->setIcon( QIcon(IconPath("edit.png")));
   ui->deleteButton->setIcon( QIcon(IconPath("delete.png")));

   m_tickCallback = new TimeoutListener( this);

   connect( ui->editButton, SIGNAL(clicked()), this, SIGNAL(editRequest()) );

   connect( &actionController, SIGNAL(activeRowChanged(int)), this, SLOT(onActiveRowChanged(int)) );
   connect( &runner, SIGNAL(timeToNextEvent(int)), this, SLOT(onTimeToNextEventChange(int)) );
   connect( &runner, SIGNAL(sequenceIsRunning(bool)), this, SLOT(onSequenceRunningChange(bool)) );

   connect( m_tickCallback, SIGNAL(timeout()), this, SLOT(onTimerTick()) );
}

SequencePlaybar::~SequencePlaybar()
{
   delete m_tickCallback;
   delete ui;
}

void SequencePlaybar::onTimeToNextEventChange(int timeMs)
{
   m_countDownMs = timeMs;

   setCountDownTimeMs(timeMs);
}

void SequencePlaybar::onActiveRowChanged(int newRow)
{
   setVisible( (newRow >= 0));
}

/**
 * update count-down display, as a fixed known time has elapsed
 */
void SequencePlaybar::onTimerTick()
{
   m_countDownMs -= TIME_REFRESH_MS;

   if (m_countDownMs >= 0)
   {
      setCountDownTimeMs( m_countDownMs);
   }
}

void SequencePlaybar::onSequenceRunningChange(bool running)
{
   if (running == false)
   {
      /* sequence paused. Stop countdown */
      m_timer->stopTimer();
      setCountDownTimeMs( -1);
   }
}

void SequencePlaybar::setCountDownTimeMs(int timeMs)
{
   if (timeMs > 0)
   {
      QTime time( 0, (timeMs / 60000) % 60, (timeMs / 1000) % 60, (timeMs % 1000) / 100 );
      ui->lcdNumber->display( time.toString("m:ss.z") );

      m_timer->triggerTimeout( TIME_REFRESH_MS, m_tickCallback );
   }
   else
   {
      ui->lcdNumber->display( QString("--"));
      m_timer->stopTimer();
   }
}

void SequencePlaybar::on_deleteButton_clicked()
{
   int answer;

   answer = QMessageBox::question( this, tr("confirm element deletion"),
                                   tr("Are you sure to delete the preset ?\n"
                                      "WARNING: Check indexes of next items after deletion!"),
                                   QMessageBox::Yes, QMessageBox::No );

   if (answer == QMessageBox::Yes)
   {
      emit deleteRequest();
   }
}
